package com.gun.management.module.raffle.service.lotterylog;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gun.management.framework.common.exception.ServiceException;
import com.gun.management.framework.common.pojo.PageResult;
import com.gun.management.framework.common.util.object.BeanUtils;
import com.gun.management.framework.mybatis.core.util.MyBatisUtils;
import com.gun.management.framework.web.core.util.WebFrameworkUtils;
import com.gun.management.module.member.dal.dataobject.user.MemberUserDO;
import com.gun.management.module.member.dal.mysql.point.MemberPointRecordMapper;
import com.gun.management.module.member.dal.mysql.user.MemberUserMapper;
import com.gun.management.module.raffle.controller.admin.lotterylog.vo.*;
import com.gun.management.module.raffle.controller.app.vo.LotteryGoodsRespVO;
import com.gun.management.module.raffle.dal.dataobject.lotterylog.LotteryLogDO;
import com.gun.management.module.raffle.dal.mysql.lottery.LotteryMapper;
import com.gun.management.module.raffle.dal.mysql.lotterylog.LotteryLogMapper;
import com.gun.management.module.raffle.dal.mysql.lotteryrecord.LotteryRecordMapper;
import com.gun.management.module.raffle.dal.mysql.lotteryrule.LotteryRuleMapper;
import com.gun.management.module.raffle.dal.mysql.lotteryruleref.LotteryRuleRefMapper;
import com.gun.management.module.raffle.enums.ErrorCodeConstants;
import com.gun.management.module.system.api.dict.DictDataApi;
import com.gun.management.module.system.api.user.AdminUserApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;

import static com.gun.management.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 用户抽奖日志 Service 实现类
 *
 * @author 测试账号
 */
@Service
@Validated
@Slf4j
public class LotteryLogServiceImpl implements LotteryLogService {

    @Resource
    private LotteryLogMapper lotteryLogMapper;

    @Resource
    private LotteryMapper lotteryMapper;

    @Resource
    private LotteryRecordMapper lotteryRecordMapper;

    @Resource
    private LotteryRuleMapper lotteryRuleMapper;

    @Resource
    private LotteryRuleRefMapper lotteryRuleRefMapper;

    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private MemberPointRecordMapper memberPointRecordMapper;

    @Resource
    private AdminUserApi userApi;

    @Resource
    private DictDataApi dictDataApi;

/*    @Resource
    private IManagementSupplyOrderApi tradeOrderApi;*/

    private final static int LOTTERY_LOG_NOT_EXISTS = 401;

    @Override
    public Long createLotteryLog(LotteryLogSaveReqVO createReqVO) {
        // 插入
        LotteryLogDO lotteryLog = BeanUtils.toBean(createReqVO, LotteryLogDO.class);

        Long userId = WebFrameworkUtils.getLoginUserId();
        lotteryLog.setCreator(String.valueOf(userId));
        lotteryLog.setCreateTime(LocalDateTime.now());

        lotteryLogMapper.insert(lotteryLog);
        // 返回
        return lotteryLog.getId();
    }

    @Override
    public void updateLotteryLog(LotteryLogSaveReqVO updateReqVO) {
        // 校验存在
        validateLotteryLogExists(updateReqVO.getId());
        // 更新
        LotteryLogDO updateObj = BeanUtils.toBean(updateReqVO, LotteryLogDO.class);

        Long userId = WebFrameworkUtils.getLoginUserId();
        updateObj.setUpdater(String.valueOf(userId));
        updateObj.setUpdateTime(LocalDateTime.now());

        lotteryLogMapper.updateById(updateObj);
    }

    /**
     * 手动推送并更新
     *
     * @param updateReqVO
     * @return
     */
    @Override
    public LotteryLogSendingOrderRespVO reSendingOrder(LotteryLogUpdateReqVO updateReqVO) {
        if (updateReqVO.getPrizeType() == 22) {
            throw new ServiceException(462, "未中奖订单，无法执行推送订单操作！");
        }

        LambdaQueryWrapper<LotteryLogDO> ruleDOLambdaQueryWrapper = Wrappers.lambdaQuery();
        ruleDOLambdaQueryWrapper.eq(LotteryLogDO::getId, updateReqVO.getLotteryLogId());
        LotteryLogDO lotteryLogDO = lotteryLogMapper.selectOne(ruleDOLambdaQueryWrapper);
        if (lotteryLogDO == null) throw new ServiceException(401, "中奖记录不存在或已被删除！");
        if (lotteryLogDO.getStatus() == 0) {
            throw new ServiceException(402, "奖品尚未被领取，无法执行推送订单操作！");
        }
        if (lotteryLogDO.getStatus() == 2) {
            throw new ServiceException(403, "奖品已领取并已下单派送，无法执行推送订单操作！");
        }

        MemberUserDO memberUserDo = memberUserMapper.selectOne(MemberUserDO::getMobile, updateReqVO.getMobile());
        if (memberUserDo == null) {
            throw new ServiceException(421, "会员用户可能不存在,无法执行推送订单操作!");
        }


//        ReqApplyTradeOrderVO reqApplyTradeOrderVO = new ReqApplyTradeOrderVO();

        LotteryGoodsRespVO lotteryGoodsRespVO = lotteryRuleMapper.selectLotteryGoodsRespVO(updateReqVO.getRuleId());
        if (lotteryGoodsRespVO == null) throw new ServiceException(821, "根据奖品编号未查询到奖品信息，可能是奖品已无库存！");
        /*reqApplyTradeOrderVO.setProductId(lotteryGoodsRespVO.getProductId());
        reqApplyTradeOrderVO.setProductSkuId(lotteryGoodsRespVO.getSkuId());
        reqApplyTradeOrderVO.setApplyCount(1); // 申请下单数量
        reqApplyTradeOrderVO.setUserId(memberUserDo.getId()); // 用户id
        reqApplyTradeOrderVO.setIsVirtual(updateReqVO.getPrizeType()); // 奖品类型*/

       /* // 如果是供应链实物或者自营商品
        if (updateReqVO.getPrizeType().intValue() == 0 || updateReqVO.getPrizeType().intValue() == 99) {
            reqApplyTradeOrderVO.setExtentData(lotteryLogDO.getExtJson().toString());
        }
        // 如果是直充
        if (updateReqVO.getPrizeType().intValue() ==3) {
            reqApplyTradeOrderVO.setExtentData(lotteryLogDO.getExtJson().toString());
        }


        CommonResult<String> result = tradeOrderApi.applyOrderByProduct(reqApplyTradeOrderVO);
        log.info("执行结果获取订单编号orderNo: " + result.getData());*/

        LambdaUpdateWrapper<LotteryLogDO> lotteryLogDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lotteryLogDOLambdaUpdateWrapper.eq(LotteryLogDO::getId, lotteryLogDO.getId());
//        lotteryLogDOLambdaUpdateWrapper.set(LotteryLogDO::getOrderNo, result.getData()); // 更改状态（为已领取状态)
        lotteryLogDOLambdaUpdateWrapper.set(LotteryLogDO::getUpdateTime, LocalDateTime.now());
        lotteryLogDOLambdaUpdateWrapper.set(LotteryLogDO::getUserId,memberUserDo.getId());
        lotteryLogDOLambdaUpdateWrapper.set(LotteryLogDO::getStatus,2); // 处理成功 奖品状态(0:待领取 1：已领取未处理 2:处理成功 3:处理失败)
        lotteryLogMapper.update(null, lotteryLogDOLambdaUpdateWrapper);

//        log.info("更新订单编号orderNo: " + result.getData() + "至中奖记录表对应的id:" + lotteryLogDO.getId() + "成功");
        LotteryLogSendingOrderRespVO respVO = new LotteryLogSendingOrderRespVO();
        respVO.setId(lotteryLogDO.getId());
        respVO.setStatus(2);
        respVO.setStatusName(dictDataApi.getDictDataLabel("prize_status",2));
//        respVO.setOrderNo( result.getData());

        return respVO;


    }

    @Override
    public void deleteLotteryLog(Long id) {
        // 校验存在
        validateLotteryLogExists(id);
        // 删除
        lotteryLogMapper.deleteById(id);
    }

    private void validateLotteryLogExists(Long id) {
        if (lotteryLogMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstants.LOTTERY_LOG_NOT_EXISTS);
        }
    }

    @Override
    public LotteryLogDO getLotteryLog(Long id) {
        return lotteryLogMapper.selectById(id);
    }




    @Override
    public PageResult<LotteryLogRespVO> getAdminLotteryLogPageList(Long userId, Long telantId, LotteryLogPageRequestVO pageReqVO) {

        IPage<LotteryLogRespVO> pageResult = lotteryLogMapper.getAdminLotteryLogPageList(MyBatisUtils.buildPage(pageReqVO),
                pageReqVO.getLotteryCategoryId(), pageReqVO.getNickName(), pageReqVO.getRuleCategoryId(), pageReqVO.getLotteryTime(), pageReqVO.getLotteryName(), pageReqVO.getPrizeName(), pageReqVO.getOrderNo(), pageReqVO.getStatus());
        return new PageResult<>(pageResult.getRecords(), pageResult.getTotal());
    }




}
